package com.csdj.server.utils;

import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName: FastDFSClient
 * @Author: ZouLi
 * @Description: 文件上传工具类
 * @Date: 2023/2/16 9:37
 **/
public class FastDFSClient {
    private static Logger log = LoggerFactory.getLogger(FastDFSClient.class);

    static {
        try{
            String filepath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filepath);
        }catch (Exception e){
            log.error("FastDFS Client Init Fail!",e);
        }
    }

    /**
     * @Description: 获取文件信息
     * @Param [groupName, remoteFileName]
     * @Return org.csource.fastdfs.FileInfo
     * @Throws
     **/
    public static FileInfo getFileInfo(String groupName, String remoteFileName){
        try {
            StorageClient storageClient = getStorageClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        }catch (IOException e){
            log.error("IO Exception: Get File from Fast DFS failed", e);
        }catch (Exception e){
            log.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }

    /**
     * @Description: 获取文件地址
     * @Param []
     * @Return java.lang.String
     * @Throws
     **/
    public static String getFilePath() throws Exception{
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getTrackerServer();
        StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
        return "http://"+storeStorage.getInetSocketAddress().getHostString()+":8888/";
    }

    /**
     * @Description: 文件上传
     * @Param [file]
     * @Return java.lang.String[]
     * @Throws
     **/
    public static String[] uploadFile(MultipartFile file){
        String name = file.getOriginalFilename();
        try {
            log.info("File Name: " + name + "File Length:" + file.getBytes().length);
        } catch (IOException e) {
            e.printStackTrace();
        }

        long startTime = System.currentTimeMillis();
        // 上传结果
        String[] uploadResult = null;
        // storage客户端
        StorageClient storageClient = null;
        try{
            // 获取storage客户端
            storageClient = getStorageClient();
            // 文件上传
            uploadResult = storageClient.upload_file(file.getBytes(), name.substring(name.lastIndexOf(".")+1), null);
        }catch (IOException e){
            log.error("IO Exception when uploadind the file:" + name, e);
        }catch (Exception e){
            log.error("Non IO Exception when uploadind the file:" + name, e);
        }
        log.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + "ms");

        // 验证上传结果
        if (uploadResult == null && storageClient != null){
            log.error("upload file fail, error code:" + storageClient.getErrorCode());
        }
        log.info("upload file successfully!!!" + "group_name:" + uploadResult[0] + ",remoteFileName:" + " " +uploadResult[1]);
        return uploadResult;
    }

    /**
     * @Description: 参数：组名，文件路径名
     * @Param [groupName, remoteFileName]
     * @Return java.io.InputStream
     * @Throws
     **/
    public static InputStream downloadFile(String groupName, String remoteFileName){
        try{
            StorageClient storageClient = getStorageClient();
            byte[] file = storageClient.download_file(groupName, remoteFileName);
            InputStream ins = new ByteArrayInputStream(file);
            return ins;
        }catch (IOException e){
            log.error("IO Exception: Get File from Fast DFS failed", e);
        }catch (Exception e){
            log.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }

    /**
     * @Description: 删除文件
     * @Param [groupName, remoteFileName]
     * @Return void
     * @Throws
     **/
    public static void deleteFile(String groupName, String remoteFileName) throws Exception{
        StorageClient storageClient = getStorageClient();
        int i = storageClient.delete_file(groupName, remoteFileName);
        log.info("delete file successfully!!!" + i);
    }

    /**
     * @Description: 获取服务端跟踪器
     * @Param []
     * @Return org.csource.fastdfs.TrackerServer
     * @Throws
     **/
    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getTrackerServer();
        return trackerServer;
    }

    /**
     * @Description: 获取客户端存储对象
     * @Param []
     * @Return org.csource.fastdfs.StorageClient
     * @Throws
     **/
    private static StorageClient getStorageClient() throws IOException {
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = new StorageClient(trackerServer, null);
        return storageClient;
    }
}
